package com.dongjiantong.app.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.enums.DjtBreedReportsStatus;
import com.dongjiantong.quarantine.model.DjtBreedReports;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtBreedReportsReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtBreedReportsWriteService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 14/11/17.
 *
 */
@Slf4j
@OpenBean
public class DjtBreedReportsController {

    @Reference(version = "1.0.0")
    private DjtBreedReportsReadService djtBreedReportsReadService;

    @Reference(version = "1.0.0")
    private DjtBreedReportsWriteService djtBreedReportsWriteService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;
    /**
     * 查询单据详情 根据 单据 ID
     * @param id 主键 ID
     * @return Response<DjtBreedReports>
     */
    @OpenMethod(
            key = "find.breed.report.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<DjtBreedReports> findById(Long id){
        if(id == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }

        try{
            DjtBreedReports djtBreedReports = djtBreedReportsReadService.findById(id);

            Map<String , Object> map = Maps.newHashMap();
            map.put("field","site_survey_photo_list");
            map.put("type1", ReportType.QUARANTINE_ORIGIN_AREA.value());
            map.put("type2",1);
            map.put("relevanceId",djtBreedReports.getId());
            List<String> site_survey_photo_list = breedReportsFileReadService.findListByType(map);
            djtBreedReports.setSite_survey_photo_list(site_survey_photo_list);
            map.put("field","quarantine_cert_photo_list");
            List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
            djtBreedReports.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
            map.clear();
            map.put("reportId",id);
            map.put("reportType",ReportType.QUARANTINE_ORIGIN_AREA.value());
            List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
            djtBreedReports.setEar_tag_numbers(ear_tag_numbers);
            return Response.ok(djtBreedReports);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端分页查询 单据list
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @param farmId 养殖场ID
     * @return Response<PageInfo<DjtBreedReports>>
     */
    @OpenMethod(
            key = "paging.breed.report.for.farm",
            paramNames = {"pageNum","pageSize","statuses","farmId"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtBreedReports>> pagingForFarm(Integer pageNum,
                                                             Integer pageSize,
                                                             List<Integer> statuses,
                                                             Long farmId){

        if(farmId == null){
            throw new OPServerException(HttpCode.FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.FARM_ID_IS_NOT_EXIST.getMessage());
        }
        Map<String , Object> map = Maps.newHashMap();
        map.put("farmId",farmId);
        map.put("statuses",statuses);
        try{
            PageInfo<DjtBreedReports> breedReportsPageInfo = djtBreedReportsReadService.pagingForFarm(pageNum,pageSize,map);
            return Response.ok(breedReportsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 官方兽医查询
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @param statuses 单据对象的list
     * @param applyStationId 申报点id
     * @param fromDate 从时间
     * @param toDate 到时间
     * @param isScale 是否是散户
     * @return Response<PageInfo<DjtBreedReports>>
     */
    @OpenMethod(
            key = "paging.breed.report.for.gov.veterinarian",
            paramNames = {"pageNum","pageSize","statuses","applyStationId","certificateStationId","fromDate","toDate","isScale"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtBreedReports>> pagingForGOVVeterinarian(Integer pageNum,
                                                                        Integer pageSize,
                                                                        List<Integer> statuses,
                                                                        Long applyStationId,
                                                                        Long certificateStationId,
                                                                        String fromDate ,
                                                                        String toDate,
                                                                        Integer isScale){

        Date start = Strings.isNullOrEmpty(fromDate) ? null : DateTime.parse(fromDate).toDate();
        Date end = Strings.isNullOrEmpty(toDate) ? null : DateTime.parse(toDate).toDate();
        Map<String , Object> map = Maps.newHashMap();
        if(start != null) map.put("start",start);
        if(end != null) map.put("end",end);
        LoginInfo loginInfo = UserUtil.getCurrentUser();
        List<Long> applyStationIds = new ArrayList<Long>();
        if(applyStationId != null){
            applyStationIds.add(applyStationId);
        }else {
            applyStationIds = loginInfo.getDeclareStationIds();
        }
        List<Long> certificateStationIds = new ArrayList<>();
        if(certificateStationId != null){
            certificateStationIds.add(applyStationId);
        }else {
            certificateStationIds = loginInfo.getCertificateStationIds();
        }
        map.put("applyStationIds",applyStationIds);
        map.put("certificateStationIds",certificateStationIds);
        if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
        if(isScale != null) map.put("isScale",isScale);
        try{
            PageInfo<DjtBreedReports> breedReportsPageInfo = djtBreedReportsReadService.pagingForFarm(pageNum,pageSize,map);
            return Response.ok(breedReportsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 协检员查询
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @param statuses 单据对象的list
     * @param farmId 养殖场ID
     * @param fromDate 从时间
     * @param toDate 到时间
     * @return Response<PageInfo<DjtBreedReports>>
     */
    @OpenMethod(
            key = "paging.breed.report.for.gov.association.inspector",
            paramNames = {"pageNum","pageSize","statuses","farmId","fromDate","toDate"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtBreedReports>> pagingForGOVAssociationInspector(@RequestParam(required = true) Integer pageNum,
                                                                        @RequestParam(required = true) Integer pageSize,
                                                                        @RequestBody(required = false) List<Integer> statuses,
                                                                        @RequestParam(required = false) Long farmId,
                                                                        @RequestParam(required = false) String fromDate ,
                                                                        @RequestParam(required = false) String toDate){

        Date start = Strings.isNullOrEmpty(fromDate) ? null : DateTime.parse(fromDate).toDate();
        Date end = Strings.isNullOrEmpty(toDate) ? null : DateTime.parse(toDate).toDate();
        Map<String , Object> map = Maps.newHashMap();
        if(start != null) map.put("start",start);
        if(end != null) map.put("end",end);
        List<Long> farmIds = new ArrayList<Long>();
        if(farmId != null){
            farmIds.add(farmId);
        }else {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            farmIds = loginInfo.getBreedFactoryIds();
        }
        map.put("farmIds",farmIds);
        if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
        try{
            PageInfo<DjtBreedReports> breedReportsPageInfo = djtBreedReportsReadService.pagingForFarm(pageNum,pageSize,map);
            return Response.ok(breedReportsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }

    }

    /**
     * 创建单据
     * @param djtBreedReports 单据对象
     * @param toStatus 到状态
     * @return Response<Long>
     */
    @Transactional
    @OpenMethod(
            key = "create.breed.report",
            paramNames = {"djtBreedReports","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> create(DjtBreedReports djtBreedReports, Integer toStatus){

        try{
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Date date = new Date();
            djtBreedReports.setCreated_at(date);
            djtBreedReports.setUpdated_at(date);
            Map<String , Object> result = djtBreedReportsWriteService.create(djtBreedReports,toStatus,loginInfo);
            return Response.ok(result);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_CREATE_FAIL.getCode(),HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 跟新单据
     * @param djtBreedReports 单据对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @Transactional
    @OpenMethod(
            key = "update.breed.report",
            paramNames = {"djtBreedReports" , "toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> update(DjtBreedReports djtBreedReports, Integer toStatus){
        if(djtBreedReports.getId() == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        try{
            Integer status = djtBreedReportsReadService.findStatusById(djtBreedReports.getId());
            if(status != null && !status.equals(djtBreedReports.getStatus().intValue())){
                throw new OPServerException(HttpCode.DOCUMENT_REPEAT_SUBMIT.getCode(),HttpCode.DOCUMENT_REPEAT_SUBMIT.getMessage());
            }
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Date date = new Date();
            djtBreedReports.setUpdated_at(date);
            Map<String , Object> resultMap = djtBreedReportsWriteService.update(djtBreedReports,toStatus,loginInfo);

            if(toStatus != null && toStatus.equals(DjtBreedReportsStatus.STAY_LICENSE.value())){
                String number = djtBreedReports.getNumber();
                //SendMessage.sendMsg(djtBreedReports.getOwner(),number.substring(number.length()-9),djtBreedReports.getCertificate_station_name(),djtBreedReports.getOwner_mobile());
            }

            return Response.ok(resultMap);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getCode(),HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }
}
